import Axios from '@/util/ajax'
import Auth from '@/util/auth'

const state = {
    token: '',
    navList: [],
    permissionList: []
}

const mutations = {
    setNavList: (state, data) => {
        console.log("setNavList() data: ", data);
        state.navList = data
    },

    setToken: (state, data) => {
        console.log("setToken", data);
        if(data){
            Auth.setToken(data)
            Auth.setLoginStatus()
        } else {
            Auth.removeToken()
            Auth.removeLoginStatus()
        }
        state.token = data
    }
}

const actions = {
    // 用户名密码登录
    loginByUserInfo({ commit }, userInfo) {
        return new Promise((resolve) => {
            Axios.post('/ajaxLogin', userInfo).then(res => {
                console.log("从登陆返回的消息：", res);
                if(res.status == 200){
                    commit('setToken', res.result.token)
                    commit('user/setName', res.result.username, { root: true })
                }
                resolve(res)
            })
        });
    },

    // 登出
    logout({commit}) {
        return new Promise((resolve) => {
            commit('setToken', '')
            commit('user/setName', '', { root: true })
            commit('tagNav/removeTagNav', '', {root: true})
            resolve()
        })
    },

    // 获取该用户的菜单列表
    getNavList({commit}){
        console.log("getNavList()");
        return new Promise((resolve) =>{
            Axios.get('/aa/auth/getMenus').then((res) => {
                commit("setNavList", res.result)
                resolve(res)
            })
        })
    },

    // 将菜单列表扁平化形成权限列表
    getPermissionList({state}){
        console.log("getPermissionList()")
        return new Promise((resolve) =>{
            let permissionList = []
            // 将菜单数据扁平化为一级
            function flatNavList(arr){
                for(let v of arr){
                    if(v.child && v.child.length){
                        flatNavList(v.child)
                    } else{
                        permissionList.push(v)
                    }
                }
            }
            flatNavList(state.navList)
            state.permissionList = permissionList
            resolve(permissionList)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
